# -*- coding: utf-8 -*-
#
#  Copyright (c) 2009 Andy Mikhailenko and contributors
#
#  This file is part of Django LJSync.
#
#  Django LJSync is free software under terms of the GNU Lesser
#  General Public License version 3 (LGPLv3) as published by the Free
#  Software Foundation. See the file README for copying conditions.
#

# django
from django.db import models
#from django.db.models import permalink
from django.db.models.signals import pre_save, post_save
from django.utils.translation import ugettext_lazy as _
#from django.contrib.auth.models import User, Message
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType

# apps
from custom_models.auto_slug_field import AutoSlugField

# this app
from ljsync.conf.settings import BLOG_ENTRY_MODEL

post_model = None
if BLOG_ENTRY_MODEL:
    app_label, model = BLOG_ENTRY_MODEL.split('.')
    try:
        entry_model = getattr(__import__('%s.models' % app_label, globals(), {}, ['']), model)
    except AttributeError, e:
        raise AttributeError, 'Wrong LJ_BLOG_ENTRY_MODEL setting: %s' % e.message

class LJPost(models.Model):
    " A post just imported from LiveJournal and waiting to be converted to a regular Post "
    security_choices = (
        (None,      'Public'),
        ('private', 'Private'),
        ('usemask', 'Fine-grained'),
    )
    subject   = models.CharField("Subject", max_length=250)
    event     = models.TextField("Body")
    eventtime = models.CharField("Date and time (raw)", max_length=50)
    pub_date  = models.DateTimeField("Date and time", max_length=50, blank=True, null=True)
    revtime   = models.IntegerField("Last updated (raw)", blank=True, null=True)
    rev_date  = models.DateTimeField("Last updated", blank=True, null=True)
    revnum    = models.IntegerField("Number of revisions", default=0,
                                    help_text='Number of times this post was edited')
    # how to locate the post in original system:
    url    = models.URLField(blank=True, null=True)
    itemid = models.IntegerField(unique=True)
    # parsing mode
    opt_preformatted = models.BooleanField(default=False)
    # categorization
    taglist = models.CharField('Tags', max_length=250, blank=True, null=True, help_text="Comma-separated list of tags")
    # more
    current_location = models.CharField("Location", max_length=250, blank=True, null=True)
    current_music    = models.CharField("Music", max_length=250, blank=True, null=True)
    current_moodid   = models.IntegerField("Mood ID (if known)", blank=True, null=True)
    current_mood     = models.CharField("Mood", max_length=250, blank=True, null=True)
    # security
    security  = models.CharField("Security", choices=security_choices, max_length=8, blank=True, null=True)
    allowmask = models.IntegerField("ACL", blank=True, null=True,
                                    help_text="If security is 'usemask' then this is defined with "\
                                              "the 32-bit unsigned int bit-mask of who is allowed to access this post.")
#    post = models.ForeignKey(Post, blank=True, null=True, verbose_name=_('Post'), related_name='lj_post',
#                             help_text=_('A post from which this LJ entry was exported or to which it was imported.'))

    # Post field
    content_type = models.ForeignKey(ContentType, null=True, blank=True, related_name="lj_post_for_%(class)s")
    object_id    = models.PositiveIntegerField(null=True, blank=True)
    local_post   = generic.GenericForeignKey()

    __unicode__ = lambda self: self.subject or u'#%s: %s' % (self.itemid, self.pub_date)

    # for admin
    get_local_post = lambda self: '<a href="%s">%s</a>' % (self.local_post.get_absolute_url(), self.local_post)
    get_local_post.short_description = 'Corresponding local post'
    get_local_post.allow_tags = True

    class Meta:
        ordering = ['-pub_date']

from ljsync.signals import fix_dates, export, crosspost

pre_save.connect(fix_dates, sender=LJPost)
pre_save.connect(export, sender=LJPost)
# allow crossposting if a model is specified:
if BLOG_ENTRY_MODEL:
    post_save.connect(crosspost, sender=entry_model)
